package com.thunbu.thunbu_meeting_system.activity

import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.cathu.lib_commonkt.base.BaseMVVMActivity
import com.hjq.toast.ToastUtils
import com.honeywell.aidc.*
import com.honeywell.rfidservice.rfid.OnTagReadListener
import com.honeywell.rfidservice.rfid.TagAdditionData
import com.honeywell.rfidservice.rfid.TagReadData
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.thunbu.lib_common.widget.CommonToolBar
import com.thunbu.thunbu_meeting_system.*
import com.thunbu.thunbu_meeting_system.databinding.*
import com.thunbu.thunbu_meeting_system.dialog.OperatPop
import com.thunbu.thunbu_meeting_system.listener.EventSimpleListener
import com.thunbu.thunbu_meeting_system.rfid.WorkMode
import com.thunbu.thunbu_meeting_system.utils.SpUtils
import com.thunbu.thunbu_meeting_system.viewMdel.InventoryTaskListViewModel
import kotlinx.android.synthetic.main.activity_inventory.view.*
import kotlinx.android.synthetic.main.include_inventory.view.*
import java.util.*
import kotlin.concurrent.thread

/**
 * 资产盘点
 * 废弃
 */
class Inventory2Activity : BaseMVVMActivity<ActivityInventoryBinding,
        InventoryTaskListViewModel>(),BarcodeReader.TriggerListener,BarcodeReader.BarcodeListener,EventSimpleListener{

    lateinit var  manager: AidcManager
    var barcodeReader: BarcodeReader?=null

    var mTagDataList= mutableListOf<TagReadData>()

    lateinit var toolBar: CommonToolBar

    private var viewDataList: MutableList<String> = ArrayList()
//    private lateinit var mAdapter: BaseVBQuickAdapter<String, InventoryTaskListItemBinding>

    private lateinit var mAdapter1: BaseVBQuickAdapter<String, InventoryListItemBinding>
    private lateinit var mAdapter2: BaseVBQuickAdapter<String, InventoryListItem3Binding>

    private lateinit var headView: View

    private var mTargetSwitchInterval = 3000
    private var mCurrentTarget = 0 // 0 A, 1 B


    @Volatile
    private var mNormalReadThreadRun = false

    @Volatile
    private var scanIng = false

    override fun onMVVMCreated() {
        headView=bindViews.linlayoutHead
        initToolBar()
        initListener()
        initView()
        initRv()
        bindAdapter1()
        initData1()
        initHeadWithData()
        initScan()


    }

    private fun initScan(){
        AidcManager.create(this) { aidcManager ->
            manager = aidcManager //获得Aidc管理器对象
            barcodeReader = manager.createBarcodeReader() //创建BarcodeReader对象
            //第二步：设置扫描属性

            //第二步：设置扫描属性
            try {
                barcodeReader?.setProperty(BarcodeReader.PROPERTY_CODE_128_ENABLED, true)
                barcodeReader?.setProperty(BarcodeReader.PROPERTY_QR_CODE_ENABLED, true)
                barcodeReader?.setProperty(
                    BarcodeReader.PROPERTY_TRIGGER_CONTROL_MODE,
                    BarcodeReader.TRIGGER_CONTROL_MODE_CLIENT_CONTROL
                )
                barcodeReader?.claim() //打开扫描功能
            } catch (e: Exception) {
                Log.i("fancl","初始化扫码枪失败:"+e.localizedMessage)
            }
            //第三步：注册Trigger监听器和Barcode监听器

            //第三步：注册Trigger监听器和Barcode监听器
            barcodeReader?.addTriggerListener(this@Inventory2Activity)
            barcodeReader?.addBarcodeListener(this@Inventory2Activity)
        }
    }

    private fun initListener(){
        bindViews.tvXzpy.setOnClickListener {
            gotoActivity<InventoryAddActivity>()
        }

        headView.lin1.setOnClickListener {
            restUi()
            headView.tv_layout1_dpd.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_dpd.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view1.visibility=View.VISIBLE

            bindAdapter1()
            initData1()
        }
        headView.lin2.setOnClickListener {
            restUi()
            headView.tv_layout2_pcs.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_pcs.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view2.visibility=View.VISIBLE
            bindAdapter2()
            initData2()
        }
        headView.lin3.setOnClickListener {
            restUi()
            headView.tv_layout3_pys.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_pys.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view3.visibility=View.VISIBLE
        }
        headView.lin4.setOnClickListener {
            restUi()
            headView.tv_layout4_pks.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_pks.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view4.visibility=View.VISIBLE
        }
    }

    private fun restUi(){
        headView.view1.visibility=View.INVISIBLE
        headView.view2.visibility=View.INVISIBLE
        headView.view3.visibility=View.INVISIBLE
        headView.view4.visibility=View.INVISIBLE
        headView.tv_layout1_dpd.setTextColor(resources.getColor(R.color.color_333333))
        headView.tv_dpd.setTextColor(resources.getColor(R.color.color_999999))
        headView.tv_layout2_pcs.setTextColor(resources.getColor(R.color.color_333333))
        headView.tv_pcs.setTextColor(resources.getColor(R.color.color_999999))
        headView.tv_layout3_pys.setTextColor(resources.getColor(R.color.color_F54545))
        headView.tv_pys.setTextColor(resources.getColor(R.color.color_999999))
        headView.tv_layout4_pks.setTextColor(resources.getColor(R.color.color_3FCB7A))
        headView.tv_pks.setTextColor(resources.getColor(R.color.color_999999))

    }

    private fun initHeadWithData(){

        headView.tv_title.text="单位资产清查"
        headView.tv_title_count.text="343"
        headView.tv_title_status.text="未完成"
        headView.tv_title_date.text="2022年10月5日"
        headView.tv_layout1_dpd.text="345"
        headView.tv_layout2_pcs.text="33"
        headView.tv_layout3_pys.text="454"
        headView.tv_layout4_pks.text="343"
    }

    private fun initRv(){
        bindViews.rlList.layoutManager = LinearLayoutManager(this)
    }


    private fun bindAdapter2(){
        mAdapter2 = bindViews.rlList.bindAdapter { item, position ->
            itemInclude.tvName.text = "笔记本电脑HP XT13PRO"
            itemInclude.tvNumber.text = "ZCY0650030010300023"
            itemInclude.tvType.text = "便携式计算机"
            itemInclude.tvAdr.text = "A幢110室"

        }
        mAdapter2.setOnItemClickListener { adapter, view, position ->
            ToastUtils.show("hahaha${position}")
        }
    }

    private fun bindAdapter1() {
        mAdapter1 = bindViews.rlList.bindAdapter { item, position ->
            tvName.text="笔记本电脑HP XT13PRO"
            tvNumber.text="343"
            tvType.text="便携式计算机"
            tvAdr.text="A幢110室"

            tvPk.setOnClickListener{

            }
            tvPc.setOnClickListener {

            }
//            ivIcon.setImageResource(item.icon)
//            tvName.text = item.text
//            tvCount.text = item.value.toString()
//            val tvName = findViewById<TextView>(R.id.tv_name)
//            val tvTip3= findViewById<TextView>(R.id.tv_tip3)
//            val tvType= findViewById<TextView>(R.id.tv_type)
//            tvName.text="笔记本电脑HP XT13PRO".plus(Random(10).nextInt())
//            tvTip3.text="上海"
//            tvType.text="便携式计算机"

//            itemInclude.tvName.text = "笔记本电脑HP XT13PRO"
//            itemInclude.tvNumber.text = "ZCY0650030010300023"
//            itemInclude.tvType.text = "便携式计算机"
//            itemInclude.tvAdr.text = "A幢110室"

        }
        mAdapter1.setOnItemClickListener { adapter, view, position ->
            ToastUtils.show("hahaha${position}")
        }
    }

    private fun initView(){
        bindViews.linAction.setOnClickListener {
            showOperatePop()
        }
    }

    private fun initData1(){
        viewDataList.add("")
        viewDataList.add("")
        viewDataList.add("")
        viewDataList.add("")
        mAdapter1.setNewData(viewDataList)
    }

    private fun initData2(){
        viewDataList.add("")
        viewDataList.add("")
        viewDataList.add("")
        viewDataList.add("")
        mAdapter2.setNewData(viewDataList)
    }



    private fun initToolBar() {
        toolBar = setToolBar(CommonToolBar::class.java)
        toolBar.setBackAction { finish() }
        toolBar.setTitle(getString(R.string.title3))
        toolBar.setSubTitleRight("开始扫描",{
            if(scanIng){  //已经在开始扫描了
                scanIng = false
                (this as TextView).setText("开始扫描")
                stopRead()
                if(mTagDataList.isNotEmpty()){
                    var result:String=""
                    mTagDataList.forEach {
                        result= result.plus(it.epcHexStr).plus(",")
                    }
                    ToastUtils.show("扫描之后的结果:"+result)
                }
            }else{
                (this as TextView).setText("停止扫描")
                scanIng = true
                read()
            }
        })
    }


    private fun lightButton(){
        bindViews.linSaoma.setBackgroundResource(R.drawable.shape_bg_3375f6_no_stock_6)
        bindViews.linSaoma.tv_sm.setTextColor(resources.getColor(R.color.white))

    }

    private fun darkButton(){
        bindViews.linSaoma.setBackgroundResource(R.drawable.shape_bg_3375f6_6)
        bindViews.linSaoma.tv_sm.setTextColor(resources.getColor(R.color.color_3375f6))
    }

    //
    override fun onTriggerEvent(triggerStateChangeEvent: TriggerStateChangeEvent) {
        try {
            barcodeReader?.light(triggerStateChangeEvent.getState()) //开关补光
            barcodeReader?.aim(triggerStateChangeEvent.getState()) //开关瞄准线
            barcodeReader?.decode(triggerStateChangeEvent.getState()) //开关解码功能
            if(triggerStateChangeEvent.state){
                lightButton()
            }else{
                darkButton()
            }
        } catch (e: Exception) {

        }
    }

    //第四步：实现触发键事件和条码事件的处理
    override fun onBarcodeEvent(barcodeReadEvent: BarcodeReadEvent) {
        val result =barcodeReadEvent.getBarcodeData()		//获取扫描数据
        runOnUiThread {
            ToastUtils.show("扫码结果:"+result)
        }

    }

    override fun onFailureEvent(p0: BarcodeFailureEvent?) {

    }


    override fun onResume() {
        super.onResume()
        if (barcodeReader != null) {
            try {
                barcodeReader?.claim()
            } catch (e: Exception) {

            }
        }
        App.instance.rfidMgr?.addEventListener(this)

    }

    override fun onPause() {
        super.onPause()
        if (barcodeReader != null) {
            barcodeReader?.release()
        }
        App.instance.rfidMgr?.removeEventListener(this)

        scanIng = false
        findViewById<TextView>(com.thunbu.lib_common.R.id.toolbar_SubtitleRight).text="开始扫描"
        stopRead()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (barcodeReader != null) {
            Log.i("fancl","onDestroy")
            barcodeReader?.removeTriggerListener(this)
            barcodeReader?.removeBarcodeListener(this)
            barcodeReader?.close()
        }
        if (manager != null) {
            manager.close()
        }
    }


    override fun onRfidTriggered(trigger: Boolean) {
        super.onRfidTriggered(trigger)
        if (!scanIng || !trigger) {
            stopRead()
        } else {
            read()
        }
    }

    var readThread:Thread?=null
    fun read(){
        if (!App.instance.isReaderAvailable()) {
            return
        }
        synchronized(mTagDataList) { mTagDataList.clear() }

        val mode = WorkMode.getInstance(App.instance.mRfidReader?.isHonReader()?:false).currentScenarioId
        // Normal mode
        mNormalReadThreadRun = true
        readThread=thread {
            val additionDataType: String = SpUtils.getString(
                getString(R.string.settings_key_addition_data), "None"
            )
            val tagAddition = TagAdditionData.get(additionDataType)
            var lastReadTime = System.currentTimeMillis()
            while (mNormalReadThreadRun) {
                val tags = App.instance.mRfidReader?.syncRead(tagAddition, 200)


                tags?.let {
                    tagListener.onTagRead(it)
                    val currentTime = System.currentTimeMillis()
                    if (mode == WorkMode.Modes.MODE_MASS_TAG_MULTI_INVENTORY.value()) {
                        if(tags.size ==0){
                            if (currentTime - lastReadTime > mTargetSwitchInterval) {
                                if (currentTime - lastReadTime > mTargetSwitchInterval) {
                                    switchTarget()
                                    lastReadTime = currentTime
                                }
                            }
                        }else{
                            lastReadTime = currentTime
                        }
                    }else{
                        lastReadTime = currentTime
                    }
                }

            }

        }
    }

    private val tagListener = OnTagReadListener{ it->
        synchronized(mTagDataList){
            it?.let { itInner->
                itInner.forEach { trd->
                   val epc = trd.getEpcHexStr()
                   val result =  mTagDataList.find { data->
                        data.epcHexStr.equals(epc)
                    }
                    if(result ==null){
                        mTagDataList.add(trd)
                    }

                }
            }
        }
    }

    private fun switchTarget() {

        App.instance.mRfidReader?.apply {
            mCurrentTarget = if (0 == mCurrentTarget) {
                this.setTarget(1)
                1
            } else {
                this.setTarget(0)
                0
            }
        }

    }

    private fun stopRead(){
        if (!App.instance.isReaderAvailable()) {
            return
        }

        // Normal mode
        mNormalReadThreadRun = false
        readThread?.apply {
            interrupt()
            readThread = null
        }
    }

    private fun showOperatePop() {
        XPopup.Builder(this).popupAnimation(PopupAnimation.NoAnimation)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true)
            .asCustom(OperatPop(this,changeOperate,false)).show()

    }

    val changeOperate= {status:Int->}

}